﻿using DotNetCoreDemo.Service.Dtos;
using FCZLM.Core.Models;
using FCZLM.Core.Repositories;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using StudentMVC.HTService;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;

namespace FZCLM.Web.Controllers
{
    public class FLoginController : Controller
    {
        private readonly IRepository<Admin, int> _adminRepository;

        public FLoginController(IRepository<Admin, int> adminRepository)
        {
            _adminRepository = adminRepository;
        }

        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Index(AdminsInput input)
        {
            var admin = _adminRepository.FirstOrDefault(x => x.LoginName == input.LoginName);
            string msg = "用户名或者密码错误，请重试！";
            bool isSuccess = false;
            if (admin != null && admin.LoginPwd == input.LoginPwd)
            {
                HttpContext.Session.SetString("a", admin.LoginName);
                msg = "登陆成功";
                isSuccess = true;

                return Json(new { msg, isSuccess });
            }
            else
            {
                msg = "用户名或者密码错误";
                isSuccess = false;
                return Json(new { msg, isSuccess });
            }

        }
        public IActionResult EditLogin()//封装
        {
            return View();
        }
        [HttpPost]
            public async Task<IActionResult> EditLogin(Admin admin )//封装
        {
           
            var model = _adminRepository.FirstOrDefault(x=>x.LoginName == HttpContext.Session.GetString("a"));
         
           
            //返回序列中的第一个元素；如果未找到该元素，则返回默认值。
            string msg = "修改失败，请重试！";
            bool isSuccess = false;//后台是否修改成功，默认是失败
            if (ModelState.IsValid)
            {
                model.LoginName = admin.LoginName;
                model.LoginPwd = admin.LoginPwd;
                isSuccess = true;
                await _adminRepository.UpdateAsync(model);
                msg = "修改成功，页面即将刷新";
            }
           
            return Json(new
            {
                isSuccess,
                msg
            });
        }
    }
}